<template>
	<div class="system-menu-container">
		<el-form :inline="true" ref="dataFormRef"  :model="param.dataForm" @keyup.enter.native="getDataList()">
			<el-form-item prop="roleName" label="角色名称">
				<el-input v-model="param.dataForm.roleName" class="task-head-search-input"  placeholder="角色名称" clearable>
				</el-input>
			</el-form-item>
			<el-form-item v-if="istenant && userInfos.tenantId === '1'" prop="tenantName" label="租户名称">
				<el-input v-model="param.dataForm.tenantName" class="task-head-search-input"  placeholder="租户名称" clearable>
				</el-input>
			</el-form-item>
			<el-button  type="primary" icon="ele-Search" @click="getDataList()">搜索</el-button>
			<el-button  type="primary" icon="ele-Refresh" @click="reSetForm(dataFormRef)">重置</el-button>
        </el-form>
		<div class="btnStyle">
			<el-button  type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
			<el-button  type="primary" icon="ele-Edit"  @click="setResEditHandle()" :disabled="dataListSelections.length !== 1">设置资源权限</el-button>
			<el-button  type="danger" icon="ele-Delete" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">删除</el-button>
		</div>
		<el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
			<el-table-column type="selection" header-align="center" align="center" width="50"/>
			<el-table-column v-if="istenant && userInfos.tenantId === '1'"
				prop="tenantName" header-align="center" align="center" label="租户"/>
			<el-table-column prop="roleName" header-align="center" align="center" label="角色名称"/>
			<el-table-column prop="remark" header-align="center" align="center" label="备注"/>
			<el-table-column prop="createTime" header-align="center" align="center" width="180" label="创建时间"/>
			<el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
				<template #default="scope">
					<el-button type="primary" link  @click="updateHandle(scope.row)" >修改</el-button>
					<el-button type="primary" link  @click="setResEditLineHandle(scope.row.tenantId, scope.row.id)"  >设置资源权限</el-button>
					<el-button type="primary" link  @click="deleteHandle(scope.row.id)"  >删除</el-button>
					<el-button type="primary" link  @click="roleUserMngHandle(scope.row.id)" >用户维护</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			@size-change="onSelectSizeChange"
			@current-change="onSelectCurrentChange"
			:pager-count="5"
			:page-sizes="[10, 50, 200]"
			v-model:current-page="param.page"
			background
			v-model:page-size="param.limit"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total" small>
		</el-pagination>
		<el-dialog :close-on-click-modal="false" :title="!submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="addOrUpdateVisible">
			<el-form :model="submitForm" :rules="dataRule" ref="submitFormRef" @keyup.enter.native="dataFormSubmit(submitFormRef)" label-width="120px">
				<el-form-item v-if="istenant && userInfos.tenantId === '1'" label="租户" prop="tenantId" >
					<el-select v-model="submitForm.tenantId" placeholder="" :filterable="true" :disabled="!(!submitForm.id)" style="width: 100%;" @change="reLoadResTree">
						<el-option v-for="(item,index) in tenantSelect" :key="item.key" :label="item.value" :value="item.key"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="角色名称" prop="roleName">
					<el-input v-model="submitForm.roleName" placeholder="角色名称"></el-input>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="submitForm.remark" placeholder="备注"></el-input>
				</el-form-item>
				<el-form-item  label="授权">
					<el-tree :data="menuList" ref="treeRoleMenuRef" node-key="id" :props="menuListTreeProps"  show-checkbox  :check-strictly="false"  :highlight-current="true" v-loading="treeLoading" style="width: 100%;">
					</el-tree>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addOrUpdateVisible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(submitFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog :close-on-click-modal="false" title="设置资源权限" v-model="roleMenuSetVisible">
			<el-tree :data="menuListOnly" ref="treeRoleMenuOnlyRef" node-key="id" :props="menuListTreeProps"  show-checkbox  :check-strictly="false"  :highlight-current="true" v-loading="treeLoading" style="width: 100%;">
			</el-tree>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="roleMenuSetVisible = false">取消</el-button>
					<el-button type="primary" @click="resOnlySubmit()">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<RoleUserMng ref="roleUserMng" @refreshDataList="getDataList"></RoleUserMng>
	</div>
</template>
<script lang="ts">
import { ref, toRefs, reactive, onMounted, nextTick, defineComponent } from 'vue';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import type { FormInstance, ElTree } from 'element-plus'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {systemApi} from '/@/api/systemapi'
import RoleUserMng from './comRoleUserMng.vue'
export default defineComponent({
	components: { RoleUserMng },
	setup() {
		const stores = useUserInfo()
		const { userInfos } = storeToRefs(stores)
		const state = reactive({
			istenant: import.meta.env.VITE_IS_TENANT,
			total: 0,
			totalSelect: 0,
			param: {
				page: 1,
				limit: 10,
				dataForm: {
					roleName: '',
					tenantName: ''
				}
			},
			dataListSelections: [],
			dataList: [],
			tenantSelect: [],
			menuList: [],
			menuListOnly: [],
			roleResours: [],
			treeLoading: false,
			menuListTreeProps: {
				children: 'childList',
				label: 'name'
			},
			dataListLoading: false,
			addOrUpdateVisible: false,
			roleMenuSetVisible: false,
			submitForm: {
				id: 0,
				roleName: '',
				remark: '',
				tenantId: import.meta.env.VITE_IS_TENANT ? '': userInfos.value.tenantId,
				resId: []
			},
			dataRule: {
				roleName: [
					{ required: true, message: '角色名称不能为空', trigger: 'blur' }
				],
				tenantId: [
					{ required: true, message: '租户不能为空', trigger: 'blur' }
				]
			},
			tempTenantId: '',
			tempRoleId: '',
			roleUserMngVisible: false
		})
		// 页面加载时
		onMounted(() => {
			getTenantSelect()
			// 列表查询
			getDataList()
		})
		const roleUserMng = ref()
		const dataFormRef = ref<FormInstance>()
		const submitFormRef = ref<FormInstance>()
		const treeRoleMenuRef = ref<InstanceType<typeof ElTree>>()
		const treeRoleMenuOnlyRef = ref<InstanceType<typeof ElTree>>()
		const getDataList = () =>{
			state.dataListLoading = true
			systemApi().queryRoleListPage(state.param).then(data => {
				if (data && data.code === 0) {
					state.dataList = data.page.list
					state.total = data.page.totalCount
				} else {
					state.dataList = []
					state.total = 0
				}
			}).catch(() => {
				//
			}).finally(() => {
				state.dataListLoading = false
			})
		}
		const getTenantSelect = () => {
			systemApi().getTenantSelect().then(data => {
				if (data && data.code === 0) {
				state.tenantSelect = data.list
				}
			})
		}
		//重置
		const reSetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.param.page = 1
			getDataList()
		}
		//打开新增弹窗
		const addOrUpdateHandle = () => {
			state.submitForm = {
				id: 0,
				roleName: '',
				remark: '',
				tenantId: import.meta.env.VITE_IS_TENANT ? '': userInfos.value.tenantId,
				resId: []
			}
			state.addOrUpdateVisible = true
			state.menuList = []
		}
		//打开新增弹窗
		const updateHandle = (row: any | undefined) => {
			state.submitForm = {
				id: row.id,
				roleName: row.roleName,
				remark: row.remark,
				tenantId: row.tenantId,
				resId: []
			}
			state.addOrUpdateVisible = true
			reLoadResTree(row.tenantId)
		}
		const setResEditHandle = () => {
			setResEditLineHandle(state.dataListSelections[0].tenantId,state.dataListSelections[0].id)
		}
		const deleteHandle = (id: string | undefined) => {
			var ids = id ? [id] : state.dataListSelections.map(item => {
			return item.id
			})
			if (!ids) {
				ElMessage.error('请选择记录！')
				return
			}
			ElMessageBox.confirm('是否确定删除所选记录', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				systemApi().deleteSysRoleInfo(ids).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('删除成功')
						getDataList()
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error("删除失败")
				})
			})
		}
		const selectionChangeHandle = (val: any) => {
			state.dataListSelections = val
		}
		// 分页改变
		const onSelectSizeChange = (val: number) => {
			state.param.limit = val
			getDataList()
		}
		// 分页改变
		const onSelectCurrentChange = (val: number) => {
			state.param.page = val;
			getDataList()
		}
		const setResEditLineHandle = (tenantId:string, id:string) => {
			state.menuListOnly = []
			state.roleMenuSetVisible = true
			state.tempTenantId = tenantId
			state.tempRoleId = id
			reLoadResTreeOnly(tenantId, id)
		}
		const roleUserMngHandle = (id:string) => {
			roleUserMng.value.openDialog(id)
		}
		const dataFormSubmit = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.validate((valid: boolean) => {
				if (valid) {
					//提交数据
					let checkResIds = treeRoleMenuRef.value!.getCheckedKeys()
					checkResIds = checkResIds.concat(treeRoleMenuRef.value!.getHalfCheckedKeys())
					const loading = ElLoading.service({
						lock: true,
						text: '处理中',
						background: 'rgba(0, 0, 0, 0.7)',
					})
					state.submitForm.resId = checkResIds
					if(!state.submitForm.id) {
						//新增
						systemApi().saveSysRoleInfo(state.submitForm).then(data => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								state.addOrUpdateVisible = false
								getDataList()
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					}else{
						systemApi().updateSysRoleInfo(state.submitForm).then(data => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								state.addOrUpdateVisible = false
								getDataList()
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					}
				}
			})
		}
		const reLoadResTree = (val:string) => {
			state.treeLoading = true
			if(!val)
			state.menuList = []
			systemApi().resetTenantRoleResTree(val, state.submitForm.id).then(data => {
				if (data) {
					state.menuList = data.tree
					state.roleResours = data.asingRes
					nextTick(() => {
						checkStation(data.asingRes)
					})
				} else {
					state.menuList = []
				}
			}).finally(() => {
				state.treeLoading = false
			})
		}
		const reLoadResTreeOnly = (tenantId:string, roleId:string) => {
			state.treeLoading = true
			if(!tenantId || !roleId)
			state.menuListOnly = []
			systemApi().resetTenantRoleResTree(tenantId, roleId).then(data => {
				if (data) {
					state.menuListOnly = data.tree
					state.roleResours = data.asingRes
					nextTick(() => {
						checkStationOnly(data.asingRes)
					})
				} else {
					state.menuListOnly = []
				}
			}).finally(() => {
				state.treeLoading = false
			})
		}
		const checkStation= (asingRes) => {
			if (asingRes.length > 0) {
			var checkArrays = new Array()
			asingRes.forEach((item, index, arr) => {
				if (treeRoleMenuRef.value!.getNode(item.menuId)) {
					if (treeRoleMenuRef.value!.getNode(item.menuId).isLeaf) {
						checkArrays.push(item.menuId)
					}
				}
			})
				treeRoleMenuRef.value!.setCheckedKeys(checkArrays, false)
			} else {
				treeRoleMenuRef.value!.setCheckedKeys([], false)
			}
		}
		const checkStationOnly = (asingRes) => {
			if (asingRes.length > 0) {
			var checkArrays = new Array()
			asingRes.forEach((item, index, arr) => {
				if (treeRoleMenuOnlyRef.value!.getNode(item.menuId)) {
					if (treeRoleMenuOnlyRef.value!.getNode(item.menuId).isLeaf) {
						checkArrays.push(item.menuId)
					}
				}
			})
				treeRoleMenuOnlyRef.value!.setCheckedKeys(checkArrays, false)
			} else {
				treeRoleMenuOnlyRef.value!.setCheckedKeys([], false)
			}
		}
		const resOnlySubmit = () => {
			let checkResIds = treeRoleMenuOnlyRef.value!.getCheckedKeys()
			checkResIds = checkResIds.concat(treeRoleMenuOnlyRef.value!.getHalfCheckedKeys())
			const loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			systemApi().setSysRoleMenu(state.tempRoleId, checkResIds).then(data => {
				if (data && data.code === 0) {
					ElMessage.success('设置成功')
					state.roleMenuSetVisible = false
					getDataList()
				} else {
					ElMessage.error(data.msg)
				}
			}).catch(() => {
				ElMessage.error("保存失败")
			}).finally(() => {
				loading.close()
			})
		}
		return {
			userInfos,
			getDataList,
			reSetForm,
			dataFormRef,
			addOrUpdateHandle,
			updateHandle,
			setResEditHandle,
			deleteHandle,
			selectionChangeHandle,
			onSelectSizeChange,
			onSelectCurrentChange,
			setResEditLineHandle,
			roleUserMngHandle,
			submitFormRef,
			dataFormSubmit,
			getTenantSelect,
			treeRoleMenuRef,
			reLoadResTree,
			treeRoleMenuOnlyRef,
			resOnlySubmit,
			roleUserMng,
			...toRefs(state),
		}
	}
})
</script>